# -*- coding: UTF-8 -*-
'''
生成词云
'''
import numpy as np
import matplotlib.pyplot as plt
import jieba

from PIL import Image
from os import path
from wordcloud import WordCloud, STOPWORDS, ImageColorGenerator

d = path.dirname(__file__)

# Read the whole text.
text = open(path.join(d, 'word.txt'), 'r',encoding='utf-8').read()

# 结巴分词
wordlist = " ".join(jieba.cut(text, cut_all=True))
print(wordlist)#输出分词之后的txt

# Image.open(path.join(d, "bg.jpg")).show()
bg_img = np.array(Image.open(path.join(d, "bg.jpg")))

# 设置停用词
# stopwords = set(STOPWORDS)
# stopwords.add("said")

# 你可以通过 mask 参数 来设置词云形状
wc = WordCloud(
  background_color="white",
  max_words=2000,
  mask=bg_img,
  max_font_size=50,
  random_state=42,
  font_path='C:/Windows/Fonts/simfang.ttf').generate(wordlist)

# create coloring from image
image_colors = ImageColorGenerator(bg_img)

# show
# 在只设置mask的情况下,你将会得到一个拥有图片形状的词云
plt.imshow(wc.recolor(color_func=image_colors), interpolation="bilinear")
plt.axis("off")
plt.show()